import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

// 定义初始状态类型
interface CounterState {
  value: number;
  step: number; // 步长，每次加减的数值
}

// 初始状态
const initialState: CounterState = {
  value: 0,
  step: 1
};

// 创建Slice
const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    // 加操作
    increment: (state) => {
      state.value += state.step;
    },
    // 减操作
    decrement: (state) => {
      state.value -= state.step;
    },
    // 重置为0
    reset: (state) => {
      state.value = 0;
    },
    // 设置步长
    setStep: (state, action: PayloadAction<number>) => {
      // 确保步长是正数
      state.step = Math.max(1, action.payload);
    },
    // 直接设置数值
    setValue: (state, action: PayloadAction<number>) => {
      state.value = action.payload;
    }
  }
});

// 导出actions
export const { increment, decrement, reset, setStep, setValue } = counterSlice.actions;

// 导出reducer
export default counterSlice.reducer;
